# Login.py（修改后）
import sys
import json
import os
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from ui.Login_ui import Ui_MainWindow
from App import Window
from UIFuctions import UIFunctions

class LoginManager:
    """登录管理类，处理所有登录相关逻辑"""
    def __init__(self):
        self.users_file = "users.json"
        self._init_user_file()

    def _init_user_file(self):
        """初始化用户数据文件"""
        if not os.path.exists(self.users_file):
            with open(self.users_file, 'w') as f:
                json.dump({}, f)

    def load_users(self):
        """加载用户数据"""
        with open(self.users_file, 'r') as f:
            return json.load(f)

    def save_users(self, users):
        """保存用户数据"""
        with open(self.users_file, 'w') as f:
            json.dump(users, f)

    def validate_login(self, username, password):
        """验证登录信息"""
        users = self.load_users()
        return username in users and users[username] == password

    def register_user(self, username, password, confirm):
        """注册新用户"""
        if password != confirm:
            return False, "两次密码输入不一致"
            
        users = self.load_users()
        if username in users:
            return False, "用户名已存在"
            
        users[username] = password
        self.save_users(users)
        return True, "注册成功"

class LoginWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("农业数据智能站 - 登录")
        self.login_manager = LoginManager()  # 实例化管理类
        self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.ui_functions = UIFunctions(self)
        self.ui_functions.enable_dragging()
   
        
        # 连接信号
        self.pushButton_4.clicked.connect(self.show_login_page)
        self.pushButton_5.clicked.connect(self.show_register_page)
        self.pushButton_6.clicked.connect(self.handle_login)
        self.pushButton_13.clicked.connect(self.handle_register)

    def show_login_page(self):
        self.stackedWidget_2.setCurrentIndex(0)

    def show_register_page(self):
        self.stackedWidget_2.setCurrentIndex(1)

    def handle_login(self):
        """处理登录请求"""
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()
        
        if self.login_manager.validate_login(username, password):
            self.main_window = Window()
            self.main_window.show()
            self.close()
        else:
            QMessageBox.warning(self, "登录失败", "用户名或密码错误")

    def handle_register(self):
        """处理注册请求"""
        username = self.lineEdit_5.text()
        password = self.lineEdit_6.text()
        confirm = self.lineEdit_7.text()
        
        success, message = self.login_manager.register_user(username, password, confirm)
        if success:
            QMessageBox.information(self, "注册成功", "账号已创建，请登录")
            self.show_login_page()
        else:
            QMessageBox.warning(self, "注册失败", message)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    login_window = LoginWindow()
    login_window.show()
    sys.exit(app.exec())